package org.example.laboratorymanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.laboratorymanagement.mapper.StudentMapper;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Student;
import org.example.laboratorymanagement.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public PageBean pageStudents(Integer page, Integer pageSize, String username, String name, String lesson) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 查询学生
        List<Student> studentsList = studentMapper.listStudents(username, name, lesson);
        Page<Student> p = (Page<Student>) studentsList;

        // 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        return pageBean;
    }

    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }

    @Override
    public void update(Student student) {
        studentMapper.update(student);
    }

    @Override
    public Student login(Student student) {
        return studentMapper.selectByUsernameAndPwd(student);
    }

    @Override
    public Student selectctById(Integer id) {
        return studentMapper.selectById(id);
    }

    @Override
    public void add(Student student) {
        studentMapper.insert(student);
    }

    @Override
    public void insertBatch(List<Student> students) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            students.stream().forEach(student -> studentMapper.insert(student));
            // 提交数据
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
        // studentMapper.insertBatch(students);
    }
}
